import URL from './url.js'
const http = ({
	type = '',
	url = '',
	param = {},
	method = '',
	isJson = true,
	needToken = true
} = {}) => {
	// uni.showLoading({
	//   title: '请求中，请耐心等待..'
	// });
	// console.log('请求之前')
	let timeStart = Date.now();
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: param,
			header: (() => {
				let base_config = {
					'content-type': isJson ? 'application/x-www-form-urlencoded' :
						'application/json',
					'pushId': uni.getStorageSync('pushId') ? uni.getStorageSync(
						'pushId') : '0adcfeb7e4d55164ac5f5b2d1fb4b0d8',
				}

				if (needToken) {
					//判断是否有token
					if (uni.getStorageSync('token')) {
						base_config['Authorization'] = uni.getStorageSync('token_type') +
							" " + uni.getStorageSync('token')
					}
					if (url.indexOf('/token') != -1) {
						base_config['Authorization'] = "Basic YnJvd3NlcjoxMjM0NTY="
					}
				}

				return base_config
			})(),
			method: method,
			dataType: 'json',
			responseType: 'text',
			complete: (res) => {
				let {
					data
				} = res
				if (data && data.code == 200) {
					return resolve(data)
				} else if (data && data.code == 401) {
					uni.$emit('killLocationTimer')
					uni.showToast({
						title: '登录失效，请重新登录',
						icon: 'none',
						duration: 2000
					});
					setTimeout(function() {
						uni.reLaunch({
							url: '/pages/login'
						});
					}, 1500)
					return reject(data || res)
				} else if (data && data.error == 'invalid_token') {
					uni.$emit('killLocationTimer')
					uni.showToast({
						title: '身份认证已经过期，请重新登录',
						icon: 'none',
						duration: 2000
					});

					uni.reLaunch({
						url: '/pages/login'
					});
				} else if (data && data.access_token) {
					return resolve(data);

				} else if (data && data.code && data.msg) {
					uni.showToast({
						title: data.msg,
						icon: 'none',
						duration: 2000
					});
				} else {
					uni.showToast({
						title: '网络连接失败' + res.errMsg,
						icon: 'none',
						duration: 2000
					});
				}
			}
		})
	})
}
// get方法
const _get = (url, param = {}, ishideloading, needToken) => {
	return http({
		url,
		param,
		method: 'get',
		ishideloading,
		needToken
	})
}
const _get1 = (url, param = {}, ishideloading) => {
	return http({
		url,
		param,
		method: 'get',
		ishideloading
	})
}
const _post = (url, param = {}, isJson, needToken) => {
	return http({
		url,
		param,
		method: 'post',
		isJson,
		needToken
	})
}


const _getLocation = () => {
	return new Promise((resolve, reject) => {
		getset(resolve, reject);
	})
}
const getMyLocation = (resolve, reject) => {
	uni.getLocation({
		type: 'gcj02',
		isHighAccuracy: true,
		highAccuracyExpireTime: 10000,
		success(res) {

			getLocationAddress(res, resolve, reject);
		},
		fail(res) {
			console.log('fail定位失败=' + JSON.stringify(res));
			console.log(res.errMsg);
			switch (res.errMsg) {
				case 'getLocation:fail auth deny': //用户没有授权
					showAlertModal();
					break;
				case 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF': //手机定位开关没有打开
					showAlertLocationSwitch();
					break;
			}
			reject(res);
		},
		complete(res) {
			console.log('complete定位完成');
		}

	})
}

const getLocationAddress = (locationInfo, resolve, reject) => {

	_get('ljfl', 'https://restapi.amap.com/v3/geocode/regeo?location=' + locationInfo.longitude + ',' + locationInfo
		.latitude + '&key=689e114a1ff925e2f6b10f252327718f&radius=1000&extensions=all', {}, true).then(
		res => {
			// console.log(res)
			if (res.status == '1') {
				locationInfo.address = res.regeocode.formatted_address;
				resolve(locationInfo);
			} else {
				uni.showToast({
					title: '地址解析异常：' + res.info,
					icon: 'none'
				})
				reject(res);
			}

		}).catch(e => {
		// console.log(e)
	})
}

const getset = (resolve, reject) => {

	uni.getSetting({
		success(res) {
			console.log(res.authSetting)
			if (res.authSetting['scope.userLocation'] != undefined && res.authSetting[
					'scope.userLocation'] != true) { //非初始化进入该页面,且未授权
				showLocationAlertModal(resolve, reject);
			} else if (res.authSetting['scope.userLocation'] == undefined) { //初始化授权
				console.log('没有')
				//先调用授权的接口，授权成功进入相机界面，拒绝的话弹出提示框
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						// 用户已经同意小程序使用系统相机功能，后续调用 uni.camera 接口不会弹窗询问
						getMyLocation(resolve, reject);
					},
					fail() {
						showLocationAlertModal(resolve, reject);
					}
				})
			} else { //授权了
				getMyLocation(resolve, reject);
			}
		}
	})
}
const showAlertLocationSwitch = (resolve, reject) => {
	uni.showModal({
		title: '提示',
		content: '手机定位开关未打开，请开启定位开关后再定位！',
		showCancel: false,
		success(res) {
			if (res.confirm) {

			} else if (res.cancel) {

			}
		}
	})
}
const showLocationAlertModal = (resolve, reject) => {

	uni.showModal({
		title: '是否授权当前位置',
		content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
		success: function(res) {
			if (res.cancel) { //点击了取消
				uni.showToast({
					title: '授权失败',
					icon: 'success',
					duration: 1000
				})
			} else if (res.confirm) { //点击了确定
				openLocationSet(resolve, reject);
			}
		}
	})
}
//在设置页面中开启授权
const openLocationSet = (resolve, reject) => {
	uni.openSetting({
		success(res) {
			console.log(res.authSetting)
			if (res.authSetting["scope.userLocation"] == true) {
				console.log('进来了')
				uni.showToast({
					title: '授权成功',
					icon: 'success',
					duration: 1000
				})
				//用户授权成功后继续定位
				getMyLocation(resolve, reject);
			} else {
				uni.showToast({
					title: '授权失败',
					icon: 'success',
					duration: 1000
				})
			}
		}
	})
}


module.exports = {
	_get,
	_get1,
	_post,
	_getLocation
}
